package uk.ac.jisc.depositmo.common;

/**
 * Copyright (c) 2011, University of Southampton
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * # Redistributions of source code must retain the above copyright notice, 
 *     this list of conditions and the following disclaimer.
 * # Redistributions in binary form must reproduce the above copyright notice, 
 *     this list of conditions and the following disclaimer in the documentation 
 *     and/or other materials provided with the distribution.
 * # Neither the name of the University of Southampton nor the names of its
 *     contributors may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *  
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
 *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
 *  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.activation.MimetypesFileTypeMap;

import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.program.Program;

/**
 * Provides utility methods for file and directory handling.
 * @author Mark Borkum <mark.borkum@gmail.com>
 *
 */
public final class FileUtils {
	/**
	 * Specifies the filename of the image that returned for files that are not associated with an installed software program. 
	 */
	private static final String DEFAULT_PROGRAM_IMAGE_FILENAME = "page_white.png";
	
	private static ImageData DEFAULT_PROGRAM_IMAGE_DATA;
	
	static {
		// Construct a new image loader.
		final ImageLoader imageLoader = new ImageLoader();
		
		if (true) {
			// Attempt to load the data for the specified image into the array.
			ImageData[] imageDataArray = imageLoader.load(FileUtils.class.getResourceAsStream(DEFAULT_PROGRAM_IMAGE_FILENAME));
			
			// If the array is null or empty, then the image has not been loaded correctly.
			if (imageDataArray == null || imageDataArray.length == 0) {
				throw new RuntimeException("Failed to load image: '" + DEFAULT_PROGRAM_IMAGE_FILENAME + "'");
			} else {
				// Otherwise, cache the first frame of the image.
				DEFAULT_PROGRAM_IMAGE_DATA = imageDataArray[0];
			}
		}
	}
	
	private static final Map<String, ImageData> FILE_EXTENSION_TO_IMAGE_DATA_MAP = new HashMap<String, ImageData>();
	
	/**
	 * Returns the icon of the program that is installed on the current machine to handle the specified file.
	 * @param file  the specified file
	 * @return  the image data for the program that is associated with the specified file
	 */
	public static ImageData getProgramImageData(File file) {
		// Split the filename into "."-separated segments. 
		String[] filenameSegments = file.getName().split("\\.");
		
		if (filenameSegments.length >= 2) {
			// The filename extension is the last segment.
			String filenameExtension = filenameSegments[filenameSegments.length - 1];
			
			// If the ImageData is cached...
			if (FILE_EXTENSION_TO_IMAGE_DATA_MAP.containsKey(filenameExtension)) {
				// Return the cached ImageData.
				return FILE_EXTENSION_TO_IMAGE_DATA_MAP.get(filenameExtension);
			} else { // Otherwise...
				// Determine the locally-installed program that is associated with the filename extension.
				Program program = Program.findProgram(filenameExtension);
				
				if (program != null) {
					// Obtain the local icon for the program.
					ImageData programImageData = program.getImageData(); 
					
					// Add the icon to the cache.
					if (programImageData != null) {
						FILE_EXTENSION_TO_IMAGE_DATA_MAP.put(filenameExtension, programImageData);
					} else {
						FILE_EXTENSION_TO_IMAGE_DATA_MAP.put(filenameExtension, DEFAULT_PROGRAM_IMAGE_DATA);
					}
				} else {
					FILE_EXTENSION_TO_IMAGE_DATA_MAP.put(filenameExtension, DEFAULT_PROGRAM_IMAGE_DATA);
				}
				
				// Return the cached ImageData.
				return FILE_EXTENSION_TO_IMAGE_DATA_MAP.get(filenameExtension);
			}
		} else {
			return DEFAULT_PROGRAM_IMAGE_DATA;
		}
	}
	
	private static final MimetypesFileTypeMap MIMETYPES_FILE_TYPE_MAP = new MimetypesFileTypeMap(FileUtils.class.getResourceAsStream("mime.types"));
	
	/**
	 * Returns the IANA MIME-type (content type) of the specified file.
	 * @param file  the specified file
	 * @return  the content type of the specified file
	 */
	public static String getContentType(File file) {
		return MIMETYPES_FILE_TYPE_MAP.getContentType(file);
	}
}
